package com.power.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.power.domain.SysUser;
import com.power.domain.SysUserRole;
import com.power.mapper.SysUserMapper;
import com.power.mapper.SysUserRoleMapper;
import com.power.service.SysUserRoleService;
import com.power.service.SysUserService;
import com.power.util.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author dingchunlin
* @description 针对表【sys_user(系统用户)】的数据库操作Service实现
* @createDate 2024-07-10 15:12:14
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{


    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 保存系统用户
     *
     * @param sysUser 系统用户对象
     * @return 成功返回1，失败返回0
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveSysUser(SysUser sysUser) {
        // 将数据进行完善
        sysUser.setCreateUserId(AuthUtils.getUserId());
        sysUser.setCreateTime(new Date());
        sysUser.setShopId(1L);
        // 密码加密
        sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
        int num = sysUserMapper.insert(sysUser);
        if (num > 0){
            // 新增用户角色关系
            Long userId = sysUser.getUserId();
            List<Long> roleIdList = sysUser.getRoleIdList();
            //判断是否有值
            if (CollectionUtils.isNotEmpty(roleIdList) && roleIdList.size() > 0){
                List<SysUserRole> sysUserRoleList = new ArrayList<>();
                roleIdList.forEach(roleId -> {
                    // 构建用户角色关系对象
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(userId);
                    sysUserRole.setRoleId(roleId);
                    // 添加到集合中
                    sysUserRoleList.add(sysUserRole);
                });
                // 批量插入用户角色关系
                sysUserRoleService.saveBatch(sysUserRoleList);
            }
        }
        return num;

    }

    /**
     * 根据用户ID查询系统用户
     * @param id 用户ID
     * @return 系统用户对象
     */
    @Override
    public SysUser querySysUserByUserId(Long id) {
        // 查询用户信息
        SysUser sysUser = sysUserMapper.selectById(id);
        // 查询用户角色关系
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, id));
        if (CollectionUtils.isNotEmpty(sysUserRoles) && sysUserRoles.size() > 0){
            // 获取角色ID列表
            List<Long> roleIdList = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            // 给用户对象添加角色列表
            sysUser.setRoleIdList(roleIdList);
        }
        return sysUser;
    }

    /**
     * 修改系统用户信息
     * @param sysUser 系统用户对象
     * @return 成功返回1，失败返回0
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer modifySysUserInfo(SysUser sysUser) {
        Long userId = sysUser.getUserId();

        // 删除原有的用户角色关系
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
               .eq(SysUserRole::getUserId, userId));
        // 新增用户角色关系
        List<Long> roleIdList = sysUser.getRoleIdList();
        //判断是否有值
        if (CollectionUtils.isNotEmpty(roleIdList) && roleIdList.size() > 0){
            List<SysUserRole> sysUserRoleList = new ArrayList<>();
            roleIdList.forEach(roleId -> {
                // 构建用户角色关系对象
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(roleId);
                // 添加到集合中
                sysUserRoleList.add(sysUserRole);
            });
            // 批量插入用户角色关系
            sysUserRoleService.saveBatch(sysUserRoleList);
        }
        // 判断密码是否修改
        if (StringUtils.hasText(sysUser.getPassword())){
            // 密码加密
            sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
        }
        return sysUserMapper.updateById(sysUser);
    }

    /**
     * 根据用户ID删除系统用户
     *
     * @param userIds 用户ID集合
     * @return 成功返回1，失败返回0
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeSysUserByUserIds(List<Long> userIds) {
        // 批量/单个删除用户角色关系
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
               .in(SysUserRole::getUserId, userIds));
        // 删除用户信息
        return sysUserMapper.deleteBatchIds(userIds) == userIds.size();
    }

}




